package com.base.themvx.v

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.LinearLayout
import android.widget.TextView
import com.base.themvx.R
import com.base.themvx.StarterIntent
import com.base.themvx.activity.CommonWebviewActivity
import com.base.themvx.isValidClick

/**
 ******************(^_^)***********************<br>
 * Author: fee<br>
 * <P>DESC:
 * 通用的 Webview 加载页面
 * </p>
 * ******************(^_^)***********************
 */
class CommonWebViewPage(context: Context) : BaseViewDelegate(context) {

    companion object Helper {
        /**
         * 以 Activity的形式加载 H5页面
         */
        fun load(context: Context, h5Url: String?, h5Title: String? = null) {
            if (h5Url.isNullOrBlank()) {
                return
            }
            StarterIntent(context, CommonWebviewActivity::class.java)
                .putExtra("title", h5Title)
                .putExtra("url", h5Url)
                .startActivity(context)
        }

        fun loadWithBaseUrl(
            context: Context,
            h5DataUrl: String?,
            h5Title: String? = null,
            baseUrl: String? = null
        ) {
            if (h5DataUrl.isNullOrBlank()) {
                return
            }
            StarterIntent(context, CommonWebviewActivity::class.java)
                .putExtra("title", h5Title)
                .putExtra("url", h5DataUrl)
                .putExtra("baseUrl", baseUrl)
                .startActivity(context)
        }

        fun buildWebView(
            context: Context,
            container: ViewGroup?,
            isNeedAttach: Boolean,
            webUrl: String,
            webBaseUrl: String? = null
        ): CommonWebViewPage {
            val intent = Intent()
            intent.putExtra("url", webUrl)
            intent.putExtra("baseUrl", webBaseUrl)
            val viewDelegate = CommonWebViewPage(context)
            val theView = viewDelegate.onCreateView(container, null)
            if (isNeedAttach) {
                container?.addView(theView)
            }
            viewDelegate.initViews(true, intent, null)
            return viewDelegate
        }
    }

    private var mWebView: WebView? = null

    private lateinit var tvTitle: TextView

    private var mCurBaseUrl = ""
    private var mCurH5Url = ""
    private var mCurAssignTitle = ""

    /**
     * 提供 的视图/布局资源 ID
     */
    override fun provideVLayoutRes(): Int {
        return R.layout.common_webview_page
    }

    override fun initViews(isInitState: Boolean) {
        super.initViews(isInitState)
        if (isInitState) {
            mDataIntent?.let {
                mCurH5Url = it.getStringExtra("url") ?: ""
                mCurAssignTitle = it.getStringExtra("title") ?: ""
                mCurBaseUrl = it.getStringExtra("baseUrl") ?: ""
            }
            tvTitle = view(R.id.tvHeadCenterTitle)
            tvTitle.text = mCurAssignTitle
            mWebView = WebView(mContext)
            val containerView: LinearLayout = view(R.id.rootView)
            val lp = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
            )
            containerView.addView(mWebView, lp)
            view<View>(R.id.ivHeadBack).setOnClickListener(this)
            commonConfigWebview()
        }
    }

    override fun initDatasAndListeners() {
        super.initDatasAndListeners()
        loadUrl(mCurH5Url)
    }

    private fun loadUrl(h5HostUrl: String?) {
        if (h5HostUrl.isNullOrBlank()) {
            return
        }
        val baseUrl = mCurBaseUrl
        if (baseUrl.isBlank()) {
            mWebView?.loadUrl(h5HostUrl)
        } else {
            mWebView?.loadDataWithBaseURL(baseUrl, h5HostUrl, "text/html", "UTF-8", null)
        }
    }

    fun reload() {
        mWebView?.reload()
    }

    private fun commonConfigWebview() {
        mWebView?.settings?.run {
//            setAppCacheEnabled(true)
            allowContentAccess = true
            // Using setJavaScriptEnabled can introduce XSS vulnerabilities into your application,
            // review carefully
            javaScriptEnabled = true
            setSupportZoom(true)
            useWideViewPort = true//设置此属性，可任意比例缩放 设置webview推荐使用的窗口
            domStorageEnabled = true
            loadWithOverviewMode = true
            builtInZoomControls = true
            javaScriptCanOpenWindowsAutomatically = true
            allowFileAccess = true
            setAllowFileAccessFromFileURLs(true)
            setSupportMultipleWindows(true)
//            setPluginsEnabled(true)
            savePassword = true
            textZoom = 100
            mediaPlaybackRequiresUserGesture = false
//            if (Api.isApiCompatible(21)) {
//                mixedContentMode = 0//允许加载H5网页时，https/http混合使用
//            }
            displayZoomControls = false//一般不需要 网页上
        }
    }

    private var mJsBridgeName = ""

    @SuppressLint("JavascriptInterface")
    fun addJavascriptInterface(bridgeObj: Any, name: String) {
        mJsBridgeName = name
        mWebView?.addJavascriptInterface(bridgeObj, name)
    }


    override fun onClick(v: View?) {
        if (!v.isValidClick()) {
            return
        }
        when (v?.id) {
            R.id.ivHeadBack -> {
                reqHostFinish()
            }

            else -> {}
        }
    }

    override fun onHostFinish() {
        super.onHostFinish()
        mWebView?.let {
            val jsBridgeName = mJsBridgeName
            if (jsBridgeName.isNotBlank()) {
                it.removeJavascriptInterface(jsBridgeName)
            }
            it.stopLoading()
            it.destroy()
        }
    }
}